import { onMounted, ref, watch } from 'vue'

export function useFontSize() {
  const fontSizeRatio = ref(1)

  const setRootFontSize = () => {
    try {
      // #ifdef H5
      // 仅H5端动态设置 font-size
      const baseSize = 12
      let scale = document.documentElement.clientWidth / 1024
      const resultScale = baseSize * Math.min(scale, 0.95)
      document.documentElement.style.fontSize = `${resultScale}px`
      // #endif
      // 小程序端无需设置，建议在 uni.scss 里写死 font-size
    } catch (e) {
    }
  }

  onMounted(() => {
    setRootFontSize()
    // #ifdef H5
    window.addEventListener('resize', setRootFontSize)
    // #endif
  })

  watch(fontSizeRatio, setRootFontSize)

  const cleanup = () => {
    // #ifdef H5
    window.removeEventListener('resize', setRootFontSize)
    // #endif
  }

  return {
    fontSizeRatio,
    cleanup,
  }
}